package database.databaseAccessObjects;

import java.util.ArrayList;
import java.util.List;

import database.DatabaseHelpers.CheckInConstants;
import database.DatabaseHelpers.VIPmeSQLiteHelper;

import database.Models.CheckIn;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DAOCheckIn {

	// Database fields
	private SQLiteDatabase database;
	private VIPmeSQLiteHelper dbHelper;
	private String[] allColumns = { CheckInConstants .COLUMN_ID,
			CheckInConstants.COLUMN_LOCATION_ID,
			CheckInConstants.COLUMN_DATE, CheckInConstants.COLUMN_POINTS };

	public DAOCheckIn(Context context) {
		dbHelper = new VIPmeSQLiteHelper(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}

	public CheckIn createCheckIn(int location_id,String date, int points) {
	
		ContentValues values = new ContentValues();
		values.put(CheckInConstants.COLUMN_LOCATION_ID, location_id);
		values.put(CheckInConstants.COLUMN_DATE, date);
		values.put(CheckInConstants.COLUMN_POINTS, points);
		long insertId = database.insert(CheckInConstants.TABLE_CHECKIN, null,
				values);
		Cursor cursor = database.query(CheckInConstants.TABLE_CHECKIN,
				allColumns, CheckInConstants.COLUMN_ID + " = " + insertId, null,
				null, null, null);
		cursor.moveToFirst();
		CheckIn ci = cursorToLocation(cursor);
		cursor.close();
		return ci;
	}

	public void deleteCheckIn(int location_id) {
		
		System.out.println("Comment deleted with id: " + location_id);
		database.delete(CheckInConstants.TABLE_CHECKIN, CheckInConstants.COLUMN_LOCATION_ID
				+ " = " + location_id, null);
	}

	public List<CheckIn> getAllCheckIns() {
		List<CheckIn> cis = new ArrayList<CheckIn>();

		Cursor cursor = database.query(CheckInConstants.TABLE_CHECKIN,
				allColumns, null, null, null, null, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			CheckIn comment = cursorToLocation(cursor);
			cis.add(comment);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return cis;
	}
	public List<CheckIn> getAllCheckInsForLocation(int locationID) {
		List<CheckIn> cis = new ArrayList<CheckIn>();

		Cursor cursor = database.query(CheckInConstants.TABLE_CHECKIN,
				allColumns, CheckInConstants.COLUMN_LOCATION_ID
				+ " = " + locationID, null, null, null, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			CheckIn ci = cursorToLocation(cursor);
			cis.add(ci);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return cis;
	}
	private CheckIn cursorToLocation(Cursor cursor) {
		CheckIn ci = new CheckIn();
		ci.setId(cursor.getInt(0));
		ci.setLocation_id(cursor.getInt(1));
		ci.setDate(cursor.getString(2));
		ci.setPoints(cursor.getInt(3));
		return ci;
	}
}
